import { onMounted, onUnmounted } from 'vue'
// @ts-ignore
import { useRouter } from 'vue-router'

interface ShortcutConfig {
  key: string
  ctrl?: boolean
  alt?: boolean
  shift?: boolean
  action: () => void
  description: string
}

export function useKeyboardShortcuts() {
  const router = useRouter()
  
  const shortcuts: ShortcutConfig[] = [
    {
      key: 'h',
      ctrl: true,
      action: () => router.push('/history'),
      description: '打开历史浏览器'
    },
    {
      key: 's',
      ctrl: true,
      action: () => router.push('/search'),
      description: '打开搜索页面'
    },
    {
      key: 'd',
      ctrl: true,
      action: () => router.push('/diff'),
      description: '打开文件对比'
    },
    {
      key: 'r',
      ctrl: true,
      action: () => router.push('/recovery'),
      description: '打开文件恢复'
    },
    {
      key: 'Home',
      action: () => router.push('/'),
      description: '返回首页'
    },
    {
      key: 'F5',
      action: () => window.location.reload(),
      description: '刷新页面'
    },
    {
      key: 'Escape',
      action: () => {
        // 关闭模态框或取消当前操作
        const event = new CustomEvent('global-escape')
        window.dispatchEvent(event)
      },
      description: '取消当前操作'
    }
  ]

  const handleKeydown = (event: KeyboardEvent) => {
    // 如果焦点在输入框中，不处理快捷键
    const target = event.target as HTMLElement
    if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.contentEditable === 'true') {
      return
    }

    for (const shortcut of shortcuts) {
      const keyMatch = event.key === shortcut.key
      const ctrlMatch = shortcut.ctrl ? event.ctrlKey : !event.ctrlKey
      const altMatch = shortcut.alt ? event.altKey : !event.altKey
      const shiftMatch = shortcut.shift ? event.shiftKey : !event.shiftKey

      if (keyMatch && ctrlMatch && altMatch && shiftMatch) {
        event.preventDefault()
        shortcut.action()
        break
      }
    }
  }

  const showShortcutsHelp = () => {
    return shortcuts.map(s => ({
      keys: [
        s.ctrl && 'Ctrl',
        s.alt && 'Alt', 
        s.shift && 'Shift',
        s.key
      ].filter(Boolean).join(' + '),
      description: s.description
    }))
  }

  onMounted(() => {
    document.addEventListener('keydown', handleKeydown)
  })

  onUnmounted(() => {
    document.removeEventListener('keydown', handleKeydown)
  })

  return {
    shortcuts: showShortcutsHelp()
  }
}